package com.hengpeng.msls.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hengpeng.msls.vo.message.ComplexTicket;
import com.hengpeng.msls.vo.message.Menu;
import com.hengpeng.msls.vo.message.Scene;
import com.hengpeng.msls.vo.message.Ticket;
import com.hengpeng.msls.vo.message.WeiXinUserVo;
import com.hengpeng.msls.vo.message.resp.Article;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

/**
 * 公众平台通用接口工具类
 * @author ChenXiaobao
 * @date 2014-3-18 下午03:14:22
 */
public class WeixinUtil
{
	private static Logger log = LoggerFactory.getLogger(WeixinUtil.class);
	/**
	 * 商户toKen
	 */
	private static Map<String, String> accessTokenMap = new HashMap<String, String>();

	/**
	 * 到期时间
	 */
	private static Map<String, Date> accessTokenTimeMap = new HashMap<String, Date>();
	
	/**
	 * 微信JS接口的临时票据
	 */
	private static Map<String,String> jsapiTicketMap= new HashMap<String, String>();
	
	/**
	 * 微信JS接口的临时票据到期时间
	 */
	private static Map<String,Date> jsapiTicketTimeMap= new HashMap<String, Date>();
	
	/**
	 * 福彩定投token到期时间
	 */
	private static Date GetAccessToken_Time;

	/**
	 * 深圳福彩token到期时间
	 */
	private static Date szfcGetAccessToken_Time;

	/**
	 * 体彩定投token到期时间
	 */
	private static Date tcdtGetAccessToken_Time;

	// 过期时间为7200秒
	private static int Expires_Period = 7200;

	/**
	 * 福彩定投token
	 */
	private static String mAccessToken;

	/**
	 * 深圳福彩token
	 */
	private static String szfcmAccessToken;

	/**
	 * 体彩定投token
	 */
	private static String tcdtmAccessToken;
	
	/**
	 * 获取access_token的接口地址（GET）
	 */
	public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	
	/**
	 * 菜单创建（POST）接口地址 限1000（次/天）
	 */
	public static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
	
	/**
	 * 创建二维码接口地址
	 */
	public static String ticket_create_url = " https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=ACCESS_TOKEN";
    /**
     * 获取用户信息接口地址
     */
	public static String wxUser_get_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	
	/**
	 * 获取jsapi接口的临时票据地址
	 */
	public static String jsapiticket_get_url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
	
	/**
	 * 客服回复信息接口地址
	 */
	public static String HuiFu_get_url = " https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN";

	
	/**
	 * 发起https请求并获取结果
	 * @param requestUrl 请求地址
	 * @param requestMethod 请求方式（GET、POST）
	 * @param outputStr 提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr)
	{
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try
		{
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// 当有数据需要提交时
			if (null != outputStr)
			{
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null)
			{
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());
		}
		catch (ConnectException ce)
		{
			log.error("Weixin server connection timed out.");
		}
		catch (Exception e)
		{
			log.error("https request error:{}", e);
		}
		return jsonObject;
	}


	/**
	 * <pre>
     * 公用获取access_token 
     * </pre>
	 * @param @return
	 * @return String
	 */
	public static String getBaseAccessToken(String appId, String appsecret)
	{
		Date accessToken_Time = accessTokenTimeMap.get(appId);
		// 首次调用获取
		if (accessTokenMap.get(appId) != null)
		{
			// 如果过期，需要重新获取
			if (HasExpired(accessToken_Time))
			{
				// 获取
				accessTokenMap.put(appId, getAccessToken(appId, appsecret));
				log.info("重新获取access_token");
			}
		}
		else
		{
			accessTokenMap.put(appId, getAccessToken(appId, appsecret));
			log.info("首次获取access_token");
		}
		return accessTokenMap.get(appId);
	}

	/**
	 * <pre>
     * 请求微信服务器获取access_token 注：每天请求限次2000次 ，每次请求access_token 有效期为7200秒
     * </pre>
	 * @param @return
	 * @return String
	 */
	public static String getAccessToken(String appId, String appsecret)
	{
		String accessToken = null;
		String requestUrl = access_token_url.replace("APPID", appId).replace("APPSECRET", appsecret);
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		// 如果请求成功
		if (null != jsonObject)
		{
			try
			{
				accessToken = jsonObject.getString("access_token");
				Expires_Period = jsonObject.getInt("expires_in");
				accessTokenTimeMap.put(appId, addTime(Expires_Period));
			}
			catch (JSONException e)
			{
				accessToken = null;
				// 获取token失败
				log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"),
						jsonObject.getString("errmsg"));
			}
		}
		return accessToken;
	}

	
	
	/**
	 * <pre>
	 * 公用获取jsapiTicket
	 * </pre>
	 * @return
	 */
	public  static String getBaseJsapiTicket(String appId, String AccessToken){
		
		Date jsapiTicket_Time = jsapiTicketTimeMap.get(appId);
			// 首次调用获取
		if (jsapiTicketMap.get(appId) != null)
		{
			// 如果过期，需要重新获取
			if (HasExpired(jsapiTicket_Time))
			{
				// 获取
				jsapiTicketMap.put(appId, getJsapiTicket(appId, AccessToken));
				log.info("重新获取jsapiTicket");
			}
		}
		else
		{
			jsapiTicketMap.put(appId, getJsapiTicket(appId, AccessToken));
			log.info("首次获取jsapiTicket");
		}
		return jsapiTicketMap.get(appId);
	}
	
	
	/**
	 * <pre>
     * 请求微信服务器获取jsapi_ticket 注：有效期为7200秒
     * </pre>
	 * @param @return
	 * @return String
	 */
	private static String getJsapiTicket(String appId,String AccessToken)
	{
		String jsapiTicket = null;
		String requestUrl =jsapiticket_get_url.replace("ACCESS_TOKEN", AccessToken);
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		// 如果请求成功
		if (null != jsonObject)
		{
			try
			{
				jsapiTicket = jsonObject.getString("ticket");
				Expires_Period = jsonObject.getInt("expires_in");
				jsapiTicketTimeMap.put(appId, addTime(Expires_Period));
			}
			catch (JSONException e)
			{
				jsapiTicket = null;
				log.error("获取jsapiTicket失败");
			}
		}
		return jsapiTicket;
	}
	
	
	
	
	
	/**
	 * <pre>
     * 福彩定投获取access_token 
     * </pre>
	 * @param @return
	 * @return String
	 */
	public static String getmAccessToken()
	{
		// 首次调用获取
		if (mAccessToken != null)
		{
			// 如果过期，需要重新获取
			if (HasExpired(GetAccessToken_Time))
			{
				// 获取
				mAccessToken = getAccessToken();
				log.info("福彩定投重新获取access_token");
			}
		}
		else
		{
			mAccessToken = getAccessToken();
			log.info("福彩定投首次获取access_token");
		}
		return mAccessToken;
	}

	/**
	 * <pre>
     * 深圳福彩获取access_token 
     * </pre>
	 * @param @return
	 * @return String
	 */
	public static String getSzfcmAccessToken()
	{
		// 首次调用获取
		if (szfcmAccessToken != null)
		{
			// 如果过期，需要重新获取
			if (HasExpired(szfcGetAccessToken_Time))
			{
				// 获取
				szfcmAccessToken = getSzfcAccessToken();
				log.info("深圳福彩重新获取access_token");
			}
		}
		else
		{
			szfcmAccessToken = getSzfcAccessToken();
			log.info("深圳福彩首次获取access_token");
		}
		return szfcmAccessToken;

	}

	/**
	 * <pre>
     * 体彩定投获取access_token 
     * </pre>
	 * @param @return
	 * @return String
	 */
	public static String getTcdtmAccessToken()
	{
		// 首次调用获取
		if (tcdtmAccessToken != null)
		{
			// 如果过期，需要重新获取
			if (HasExpired(tcdtGetAccessToken_Time))
			{
				// 获取
				tcdtmAccessToken = getTcdtAccessToken();
				log.info("体彩定投重新获取access_token");
			}
		}
		else
		{
			tcdtmAccessToken = getTcdtAccessToken();
			log.info("体彩定投首次获取access_token");
		}
		return tcdtmAccessToken;

	}

	/**
	 * <pre>
     * 请求微信服务器获取access_token 注：每天请求限次2000次 ，每次请求access_token 有效期为7200秒
     * </pre>
	 * @param @return
	 * @return String
	 */
	public static String getAccessToken()
	{
		String accessToken = null;
		String requestUrl = access_token_url.replace("APPID", MessageUtil.appId).replace("APPSECRET",
				MessageUtil.appSecret);
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		// 如果请求成功
		if (null != jsonObject)
		{
			try
			{
				accessToken = jsonObject.getString("access_token");
				Expires_Period = jsonObject.getInt("expires_in");
				GetAccessToken_Time = addTime(Expires_Period);
			}
			catch (JSONException e)
			{
				accessToken = null;
				// 获取token失败
				log.error("福彩定投获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"),
						jsonObject.getString("errmsg"));
			}
		}
		return accessToken;
	}

	/**
	 * <pre>
     * 深圳福彩请求微信服务器获取access_token 注：每天请求限次2000次 ，每次请求access_token 有效期为7200秒
     * </pre>
	 * @param @return
	 * @return String
	 */
	public static String getSzfcAccessToken()
	{
		String szfcmAccessToken = null;
		String requestUrl = access_token_url.replace("APPID", MessageUtil.szfcAppId).replace("APPSECRET",
				MessageUtil.szfcAppSecret);
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		// 如果请求成功
		if (null != jsonObject)
		{
			try
			{
				szfcmAccessToken = jsonObject.getString("access_token");
				Expires_Period = jsonObject.getInt("expires_in");
				szfcGetAccessToken_Time = addTime(Expires_Period);
			}
			catch (JSONException e)
			{
				szfcmAccessToken = null;
				// 获取token失败
				log.error("深圳福彩获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"),
						jsonObject.getString("errmsg"));
			}
		}
		return szfcmAccessToken;
	}

	/**
	 * <pre>
     * 体彩定投请求微信服务器获取access_token 注：每天请求限次2000次 ，每次请求access_token 有效期为7200秒
     * </pre>
	 * @param @return
	 * @return String
	 */
	public static String getTcdtAccessToken()
	{
		String tcdtmAccessToken = null;
		String requestUrl = access_token_url.replace("APPID", MessageUtil.tcdtAppId).replace("APPSECRET",
				MessageUtil.tcdtAppSecret);
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		// 如果请求成功
		if (null != jsonObject)
		{
			try
			{
				tcdtmAccessToken = jsonObject.getString("access_token");
				Expires_Period = jsonObject.getInt("expires_in");
				tcdtGetAccessToken_Time = addTime(Expires_Period);
			}
			catch (JSONException e)
			{
				tcdtmAccessToken = null;
				// 获取token失败
				log.error("深圳福彩获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"),
						jsonObject.getString("errmsg"));
			}
		}
		return tcdtmAccessToken;
	}

	
	/**
	 * 创建菜单
	 * @param menu 菜单实例
	 * @param accessToken 有效的access_token
	 * @return 0表示成功，其他值表示失败
	 */
	public static int createMenu(Menu menu, String accessToken)
	{
		int result = 0;

		// 拼装创建菜单的url
		String url = menu_create_url.replace("ACCESS_TOKEN", accessToken);
		// 将菜单对象转换成json字符串
		String jsonMenu = JSONObject.fromObject(menu).toString();
		// 调用接口创建菜单
		JSONObject jsonObject = httpRequest(url, "POST", jsonMenu);

		if (null != jsonObject)
		{
			if (0 != jsonObject.getInt("errcode"))
			{
				result = jsonObject.getInt("errcode");
				log.error("创建菜单失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
			}
		}
		return result;
	}

	/**
	 * <pre>
     * 创建永久二维码ticket
     * </pre>
	 * @param @return
	 * @return String
	 */
	public static String createTicket(ComplexTicket ticket,String appId, String appsecret)
	{
		String ket = null;
		String at = getBaseAccessToken(appId, appsecret);
		
		if (at != null)
		{
			// 拼装创建ticket的url
			String url = ticket_create_url.replace("ACCESS_TOKEN", at);

			// 将对象转换成json字符串
			String jsonTicket = JSONObject.fromObject(ticket).toString();

			// 调用接口创建永久二维码ticket
			JSONObject jsonObject = httpRequest(url, "POST", jsonTicket);

			// 如果请求成功
			if (null != jsonObject)
			{
				try
				{
					ket = jsonObject.getString("ticket");
				}
				catch (JSONException e)
				{
					ket = null;
					log.error("创建二维码ticket失败:{} errmsg:{}", jsonObject.getInt("errcode"),
							jsonObject.getString("errmsg"));
				}
			}
		}

		return ket;
	}

	/**
	 * <pre>
	    * 返回二维码图片地址
	    * </pre>
	 * @param @param ketInt
	 * @param @return
	 * @return String
	 */
	public static String CreateExpire(String ketInt, String appId, String appsecret)
	{

		String ticket = WeixinUtil.createTicket(getTicket(ketInt), appId,appsecret);

		return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;
	}

	/**
	 * <pre>
	    * 拼接请求创建ticket的json
	    * </pre>
	 * @param @return
	 * @return JSONObject
	 */
	private static ComplexTicket getTicket(String ketInt)
	{

		Ticket ti = new Ticket();
		ti.setScene_id(ketInt);
		Scene sc = new Scene();
		sc.setScene(ti);

		ComplexTicket co = new ComplexTicket();
		co.setAction_name("QR_LIMIT_SCENE");
		co.setAction_info(sc);

		return co;
	}

	/**
	 * <pre>
	 * 获取用户信息
	 * </pre>
	 * @param @return
	 * @return WeiXinUserVo
	 */
	public static WeiXinUserVo getWeiXinUser(String openid, String accessToken)
	{
		WeiXinUserVo wx = null;
		// 拼装创建菜单的url
		String url = wxUser_get_url.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openid);
		// 调用接口创建菜单
		JSONObject jsonObject = httpRequest(url, "POST", null);
		// 如果请求成功
		if (null != jsonObject)
		{
			try
			{ 
				wx = new WeiXinUserVo();
				if(jsonObject.getString("subscribe").equals("0")){
					wx.setSubscribe(jsonObject.getString("subscribe"));
				}else{
					wx.setCity(jsonObject.getString("city"));
					wx.setCountry(jsonObject.getString("country"));
					wx.setHeadimgurl(jsonObject.getString("headimgurl"));
					wx.setNickname(jsonObject.getString("nickname"));
					wx.setOpenid(jsonObject.getString("openid"));
					wx.setProvince(jsonObject.getString("province"));
					wx.setSex(jsonObject.getString("sex"));
					wx.setLanguage(jsonObject.getString("language"));
					wx.setSubscribe_time(jsonObject.getString("subscribe_time"));
					wx.setSubscribe(jsonObject.getString("subscribe"));
				}
				
			}
			catch (JSONException e)
			{
				wx = null;
				// 获取用户信息失败
				log.error("获取用户信息失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
			}
		}
		return wx;
	}


	
	public static String huiFuMessageNews(String openId,List<Article> article ,String ACCESS_TOKEN )
	{

		JSONObject a = new JSONObject();
		a.put("touser", openId);
		a.put("msgtype", "news");
		JSONObject b = new JSONObject();
		b.put("articles",article);
		a.put("news", b);
		// 拼装创建菜单的url
		String url = HuiFu_get_url.replace("ACCESS_TOKEN", ACCESS_TOKEN);
		// 调用接口创建菜单
		httpRequest(url, "POST", a.toString());
		return null;

	}

	/**
	 * <pre>
	    *  判断Access_token是否过期
	    * </pre>
	 * @param @return
	 * @return Boolean
	 * @throws
	 */

	private static Boolean HasExpired(Date token_time)
	{

		if (token_time != null)
		{
			// 过期时间，允许有一定的误差，一分钟。获取时间消耗
			if (new Date().after(token_time))
			{
				return true;
			}
		}
		return false;
	}

	/**
	 * 将微信消息中的CreateTime转换成标准格式的时间（yyyy-MM-dd HH:mm:ss）
	 * @param createTime 消息创建时间
	 * @return
	 */
	public static String formatTime(String createTime)
	{
		// 将微信传入的CreateTime转换成long类型，再乘以1000
		long msgCreateTime = Long.parseLong(createTime) * 1000L;
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(new Date(msgCreateTime));
	}

	/**
	 * <pre>
	    * 格式化时间
	    * </pre>
	 * @param @param createTime
	 * @param @return
	 * @return String
	 */
	public static String formatDate(Date date)
	{
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		return format.format(date);
	}

	/**
	 * <pre>
	    * 时间加减秒数
	    * </pre>
	 * @param @param time
	 * @param @return
	 * @return Date
	 */
	public static Date addTime(int time)
	{
		Date rtn = null;
		Calendar cale = Calendar.getInstance();
		Date date = new Date();
		cale.setTime(date);
		cale.add(13, time - 60);
		rtn = cale.getTime();
		return rtn;
	}
	
	/**
	 * <pre>
	 * 生成jsapi签名signature
	 * </pre>
	 * @param jsapi_ticket
	 * @param url
	 * @return
	 */
	  public static Map<String, String> sign(String jsapi_ticket, String url) {
	        Map<String, String> ret = new HashMap<String, String>();
	        String nonce_str = create_nonce_str();
	        String timestamp = create_timestamp();
	        String string1;
	        String signature = "";

	        //注意这里参数名必须全部小写，且必须有序
	        string1 = "jsapi_ticket=" + jsapi_ticket +
	                  "&noncestr=" + nonce_str +
	                  "&timestamp=" + timestamp +
	                  "&url=" + url;
	        try
	        {
	            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
	            crypt.reset();
	            crypt.update(string1.getBytes("UTF-8"));
	            signature = byteToHex(crypt.digest());
	        }
	        catch (NoSuchAlgorithmException e)
	        {
	            e.printStackTrace();
	        }
	        catch (UnsupportedEncodingException e)
	        {
	            e.printStackTrace();
	        }

	        ret.put("url", url);
	        ret.put("jsapi_ticket", jsapi_ticket);
	        ret.put("nonceStr", nonce_str);
	        ret.put("timestamp", timestamp);
	        ret.put("signature", signature);

	        return ret;
	    }

	    private static String byteToHex(final byte[] hash) {
	        Formatter formatter = new Formatter();
	        for (byte b : hash)
	        {
	            formatter.format("%02x", b);
	        }
	        String result = formatter.toString();
	        formatter.close();
	        return result;
	    }
	    
	    /**
	     * <pre>
	     * 生成随机字符串
	     * </pre>
	     * @return
	     */
	    private static String create_nonce_str() {
	        return UUID.randomUUID().toString();
	    }
	    /**
	     * <pre>
	     * 生成时间戳
	     * </pre>
	     * @return
	     */
	    private static String create_timestamp() {
	        return Long.toString(System.currentTimeMillis() / 1000);
	    }
	
	public static void main(String[] args)
	{
		String url = CreateExpire("1001", "wxb597d5c6d9b3825d","192e439424c073f125573bd862bd75a7" );
		System.out.println(url);

	}

}
